﻿using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;

namespace WTAppletProjectHTTPS.Controllers
{
   
    public class QCSamplingFinishedFrameQueryController : ApiController
    {
        private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] QCSamplingFinishedFrameQuery QCSFFQ)
        {
            ReturnObjectQuery RO = new ReturnObjectQuery();
            if (QCSFFQ.PageNumber <= 0 || QCSFFQ.PageSize <= 0)
            {
               
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "分页参数无效";
                RO.Data = null;
                Logger.Error("分页参数无效");
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }

            try
            {
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
                {
                    await connection.OpenAsync();

                    var whereClause = "WHERE 1=1";
                    if (QCSFFQ.QCSFF_ID != 0)
                    {
                        whereClause += " AND QCSID = @ID";
                    }
                    if (QCSFFQ.QCSFF_InspectionDate.HasValue)
                    {
                        whereClause += " AND QCSInspectionDate = @InspectionDate";
                    }
                    if (!string.IsNullOrEmpty(QCSFFQ.QCSFF_Inspector))
                    {
                        whereClause += " AND QCSInspector LIKE @Inspector";
                    }
                    if (!string.IsNullOrEmpty(QCSFFQ.QCSFF_InspectionModel))
                    {
                        whereClause += " AND QCSInspectionModel LIKE @InspectionModel";
                    }
                    if (!string.IsNullOrEmpty(QCSFFQ.QCSFF_InspectionTiming))
                    {
                        whereClause += " AND QCSInspectionTiming LIKE @InspectionTiming";
                    }
                    if (QCSFFQ.QCSFF_SampleQuantity > 0)
                    {
                        whereClause += " AND QCSSampleQuantity = @SampleQuantity";
                    }
                    if (!string.IsNullOrEmpty(QCSFFQ.QCSFF_PhotoUpload))
                    {
                        whereClause += " AND QCSPhotoUpload LIKE @PhotoUpload";
                    }

                    var query = $@"
                        SELECT 
                            QCSID, QCSInspectionDate, QCSInspector, QCSInspectionModel, QCSInspectionTiming, 
                            QCSSampleQuantity, QCSPhotoUpload,QCSCreateCreator,QCSCreateTime,
                            COUNT(*) OVER() AS TotalCount
                        FROM 
                            (SELECT 
                                QCSID, QCSInspectionDate, QCSInspector, QCSInspectionModel, QCSInspectionTiming, 
                                QCSSampleQuantity, QCSPhotoUpload,QCSCreateCreator,QCSCreateTime,
                                ROW_NUMBER() OVER(ORDER BY QCSID) AS RowNum
                             FROM QCSamplingFinishedFrame {whereClause}) AS Result
                        WHERE 
                            RowNum BETWEEN @StartRow AND @EndRow
                        ORDER BY RowNum";

                    int startRow = (QCSFFQ.PageNumber - 1) * QCSFFQ.PageSize + 1;
                    int endRow = QCSFFQ.PageNumber * QCSFFQ.PageSize;

                    var parameters = new List<SqlParameter>
                    {
                        new SqlParameter("@StartRow", SqlDbType.Int) { Value = startRow },
                        new SqlParameter("@EndRow", SqlDbType.Int) { Value = endRow }
                    };
                    if (QCSFFQ.QCSFF_ID != 0)
                    {
                        parameters.Add(new SqlParameter("@ID", SqlDbType.Int) { Value = QCSFFQ.QCSFF_ID });
                    }
                    if (QCSFFQ.QCSFF_InspectionDate.HasValue)
                    {
                        parameters.Add(new SqlParameter("@InspectionDate", SqlDbType.DateTime) { Value = QCSFFQ.QCSFF_InspectionDate.Value });
                    }
                    if (!string.IsNullOrEmpty(QCSFFQ.QCSFF_Inspector))
                    {
                        parameters.Add(new SqlParameter("@Inspector", SqlDbType.NVarChar, 50) { Value = $"%{QCSFFQ.QCSFF_Inspector}%" });
                    }
                    if (!string.IsNullOrEmpty(QCSFFQ.QCSFF_InspectionModel))
                    {
                        parameters.Add(new SqlParameter("@InspectionModel", SqlDbType.NVarChar, 50) { Value = $"%{QCSFFQ.QCSFF_InspectionModel}%" });
                    }
                    if (!string.IsNullOrEmpty(QCSFFQ.QCSFF_InspectionTiming))
                    {
                        parameters.Add(new SqlParameter("@InspectionTiming", SqlDbType.NVarChar, 50) { Value = $"%{QCSFFQ.QCSFF_InspectionTiming}%" });
                    }
                    if (QCSFFQ.QCSFF_SampleQuantity > 0)
                    {
                        parameters.Add(new SqlParameter("@SampleQuantity", SqlDbType.Int) { Value = QCSFFQ.QCSFF_SampleQuantity });
                    }
                    if (!string.IsNullOrEmpty(QCSFFQ.QCSFF_PhotoUpload))
                    {
                        parameters.Add(new SqlParameter("@PhotoUpload", SqlDbType.NVarChar, 500) { Value = $"%{QCSFFQ.QCSFF_PhotoUpload}%" });
                    }

                    using (var command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters.ToArray());
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            if (!reader.HasRows)
                            {
                                Logger.Warn("未找到记录");
                                RO.Status = HttpStatusCode.NotFound;
                                RO.Message = "未找到记录";
                                RO.Data = null;
                                return Request.CreateResponse(HttpStatusCode.NotFound, RO);
                            }

                            var records = new List<QCSamplingFinishedFrame>();
                            int totalCount = 0;
                            while (await reader.ReadAsync())
                            {
                                if (totalCount == 0)
                                {
                                    totalCount = reader.GetInt32(reader.GetOrdinal("TotalCount"));
                                }

                                records.Add(new QCSamplingFinishedFrame
                                {
                                    QCSFF_ID = reader.GetInt32(reader.GetOrdinal("QCSID")),
                                    QCSFF_InspectionDate = reader.GetDateTime(reader.GetOrdinal("QCSInspectionDate")),
                                    QCSFF_Inspector = reader.GetString(reader.GetOrdinal("QCSInspector")),
                                    QCSFF_InspectionModel = reader.GetString(reader.GetOrdinal("QCSInspectionModel")),
                                    QCSFF_InspectionTiming = reader.GetString(reader.GetOrdinal("QCSInspectionTiming")),
                                    QCSFF_SampleQuantity = reader.GetInt32(reader.GetOrdinal("QCSSampleQuantity")),
                                    QCSFF_PhotoUpload = reader.GetString(reader.GetOrdinal("QCSPhotoUpload")),
                                    QCSFF_CreateCreator = reader.GetString(reader.GetOrdinal("QCSCreateCreator")),
                                    QCSFF_CreateTime = reader.GetDateTime(reader.GetOrdinal("QCSCreateTime"))
                                });
                            }

                            Logger.Info("查询成功");
                            RO.Status = HttpStatusCode.OK;
                            RO.Message = "OK";
                            RO.Data = records;
                            RO.TotalCount = totalCount;
                            RO.PageNumber = QCSFFQ.PageNumber;
                            RO.PageSize = QCSFFQ.PageSize;
                            return Request.CreateResponse(HttpStatusCode.OK, RO);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("查询失败: " + ex.Message);
                RO.Status = HttpStatusCode.InternalServerError;
                RO.Message = "Error: " + ex.Message;
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
            }
        }
    }
}
